<template>
  <div class="login-contain">
    <div class="login-wrap">
      <h1 class="title">博客管理系统</h1>
      <el-tabs v-model="activeName" @tab-click="handleClick">
         <!-- 登录 -->
        <el-tab-pane label="登录" name="first">
          <el-form :model="loginForm" status-icon :rules="rules2" ref="loginForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户id" prop="username">
              <el-input v-model.number="loginForm.username"></el-input>
            </el-form-item>
            <el-form-item  label="密码" prop="password" >
             <el-input v-model="loginForm.password" type="password" autocomplete="off"></el-input>

            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitLoginForm('loginForm')">登录</el-button>
              <el-button @click="resetForm('loginForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- 注册 -->
        <el-tab-pane label="注册" name="second">
          <el-form :model="registForm" status-icon :rules="rules" ref="registForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户id" prop="username">
              <el-input v-model.number="registForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="registForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="registForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('registForm')">注册</el-button>
              <el-button @click="resetForm('registForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    var checkUserid = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'))
      }
      setTimeout(() => {
        if (!/^[a-zA-Z0-9_-]{5,16}$/.test(value)) {
          callback(new Error('用户id格式错误'))
        } else {
          callback()
        }
      }, 1000)
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (!/^[a-zA-Z0-9_-]{6,16}$/.test(value)) {
          callback(new Error('密码格式错误'))
        } else {
          callback()
        }
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      registForm: {
        password: '',
        checkPass: '',
        username: ''
      },
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        username: [
          { validator: checkUserid, trigger: 'blur' }
        ]
      },
      rules2: {
        username: [
          { validator: checkUserid, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      activeName: 'first'
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http({ data: this.registForm, url: '/user/regist', method: 'post' })
          console.log(res)
          if (res.code !== 0) return this.$message.error('注册失败')
          this.$message.success('注册成功')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitLoginForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http({ data: this.loginForm, url: '/user/login', method: 'post' })
          if (res.code !== 0) return this.$message.error('登录失败')
          this.$message.success('登录成功')
          // 1、将登陆成功之后的token, 保存到客户端的sessionStorage中; localStorage中是持久化的保存
          //   1.1 项目中出现了登录之外的其他API接口，必须在登陆之后才能访问
          //   1.2 token 只应在当前网站打开期间生效，所以将token保存在sessionStorage中
          window.sessionStorage.setItem('token', res.result.token)
          window.sessionStorage.setItem('user', JSON.stringify(res.result.user))
          this.$store.dispatch('user/setToken', res.result.token)
          this.$store.dispatch('user/setUser', res.result.user)
          // 2、通过编程式导航跳转到后台主页, 路由地址为：/home
          this.$router.push('/article-list')
          console.log(res)
        } else {
          console.log('校验失败!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    handleClick (tab, event) {
      console.log(tab, event)
    }
  }
}
</script>
<style lang="less" scoped>
.login-contain {
  width: 100%;
  height: 100vh;
  background-color: #eef1f6;

  .login-wrap {
    .title {
      text-align: center;
    }

    width: 500px;
    height: 300px;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  @media screen and ( max-width:700px) {
   .login-wrap{

     width:330px
     }

  }
}
</style>
